from apscheduler.schedulers.blocking import BlockingScheduler

from tools.loggingConfig import logger
from settings import WeChatPublicPlatform, allUserInfo

# 初始化微信公众平台配置
wx = WeChatPublicPlatform()

# 初始化调度器
scheduler = BlockingScheduler(timezone="Asia/Shanghai")

# 定时更新accessToken
scheduler.add_job(wx.getAccessToken, trigger="interval", hours=wx.intervalTimeForUpdateAccessToken)

# 调度任务进行广播
for name, userInfo in allUserInfo.items():
    for dateString, templateMethodList in userInfo["customNeedTemplateMethod"].items():
        date = dateString.split(":")
        hour = int(date[0])
        minute = int(date[1])

        # 遍历用户自定义方法customNeedTemplateMethod
        for templateMethod in templateMethodList:
            kwargs = {
                "userOpenID": userInfo["userOpenId"],
                "templateMethod": templateMethod,
            }
            kwargs.update(userInfo["templateMethodKwargs"])

            scheduler.add_job(wx.sendMsg, 'cron', kwargs=kwargs, hour=hour, minute=minute)
            logger.info(f"添加定时任务：时间：{dateString}，用户：{name}，任务：{templateMethod.__name__}")

            # 该方法是否需要分享给其他用户
            for shareUserName, shareTemplateMethodList in userInfo["shareUserList"].items():
                if templateMethod in shareTemplateMethodList:
                    kwargs["userOpenID"] = allUserInfo[shareUserName]["userOpenId"]

                    scheduler.add_job(wx.sendMsg, 'cron', kwargs=kwargs, hour=hour, minute=minute)
                    logger.info(
                        f"添加分享定时任务：时间：{dateString}，用户：{name}，分享的用户：{shareUserName}，任务：{templateMethod.__name__}")

# 启动调度器
scheduler.start()
